package com.yumeng.webapp.controller;

import com.yumeng.common.api.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wxd
 * @date 2024/7/12 上午10:32
 */
@Slf4j
@RestController
//@ApiSupport(order = 1)
@Tag(name = "SecurityController", description = "Security接口集合")
@RequestMapping("/security")
public class SecurityController {


    @Operation(summary = "获取Security中当前用户信息")
    @GetMapping("/getAuthentication.do")
    public ApiResult getAuthentication(HttpSession session) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return ApiResult.successData(authentication);
    }


    @Operation(summary = "从Session中获取当前用户信息")
    @GetMapping("/getSecurityContextFromSession.do")
    public ApiResult getSecurityContextFromSession(HttpSession session) {
        SecurityContext currUser = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return ApiResult.successData(currUser);
    }

    @Operation(summary = "测试ServletApi")
    @GetMapping("/testServletApi.do")
    public ApiResult testServletApi(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        SecurityContext currUser = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        Map<String, Object> map = new HashMap<>();
        map.put("session.getId()", session.getId());
        map.put("request.getSession().getId()", request.getSession().getId());
        map.put("request.getRequestedSessionId()", request.getRequestedSessionId());

        map.put("remoteUser", request.getRemoteUser());
        map.put("userPrincipal", request.getUserPrincipal());
        map.put("isUserInRole", request.isUserInRole("admin"));
        map.put("securityContext", currUser);
        return ApiResult.successData(map);
    }

}
